<template>
	<view class="container" :class="{night: isNight}" @click="toggleControl">
		<!-- 顶部导航栏 -->
		<view class="header" v-show="showControl">
			<view class="left">
				<text class="back-icon" @click="backDetail()">←</text>
				<text class="title">{{bookTitle}}</text>
			</view>
			<text class="chapter">{{currentChapter}}</text>
		</view>

		<!-- 内容区域 -->
		<scroll-view class="content" :style="{fontSize: fontSize + 'px', lineHeight: lineHeight + 'px'}" scroll-y
			@scroll="onScroll" :scroll-top="scrollTop" scroll-with-animation show-scrollbar @scrolltolower="scrollBottom">
			<!-- 	<view>
		{{title}}
	</view> -->
			<view style="padding: 0 50rpx;">
				<text class="text">{{content}}</text>
			</view>

		</scroll-view>

		<!-- 底部控制栏 -->
		<view class="footer" v-show="showControl">
			<view class="progress">
				<!-- <text>{{progress}}%</text> -->
			</view>
			<view class="controls">
				<view class="btn" @click="changeFontSize(-2)">
					<text>A-</text>
				</view>
				<view class="btn" @click="toggleNight">
					<text>{{ isNight ? '日间' : '夜间' }}</text>
				</view>
				<view class="btn" @click="showChapterList">
					<text>目录</text>
				</view>
				<view class="btn" @click="changeFontSize(2)">
					<text>A+</text>
				</view>
			</view>
		</view>
	</view>

	<uni-popup ref="popupRef" type="left">
		<view class="catalog">
			<view class="catalog-title">小说目录 共{{novel.chapterCount}}章</view>
			<view class="chapter-list">
				<scroll-view>
					<view v-for="(chapter, index) in novel.chapters" :key="index" @click="goToChapter(chapter.id)">
						<view class="chapter-title">{{chapter.index}}.{{ chapter.title }}</view>
						<view style="color: #999;" v-if="chapterId==chapter.id">当前章节</view>
						<view class="chapter-divider"></view>
					</view>
				</scroll-view>
			</view>
			<!--        <view class="pagination">
            <button :disabled="currentPage === 1" @click="prevPage">上一页</button>
            <span>{{ currentPage }} / {{ totalPages }}</span>
            <button :disabled="currentPage === totalPages" @click="nextPage">下一页</button>
          </view> -->
		</view>
	</uni-popup>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import {
		onLoad,
		onReachBottom
	} from '@dcloudio/uni-app'
	import {
		loginBefore,
		baseUrl
	} from '../../static/js/util.js'
	// 响应式数据
	const bookTitle = ref('无')
	let scrollTop=ref(0)
	const currentChapter = ref('无')
	const content = ref('')
	let lastContent=ref()
	const showControl = ref(true)
	const isNight = ref(false)
	const fontSize = ref(16)
	const lineHeight = computed(() => fontSize.value + 12)
	const progress = ref(0)
	let bookId = ''
	let authorization = ''
	const chapterId = ref()

	let novel = ref()

	function backDetail() {
		uni.navigateTo({
			url: '/pages/bookCategory/bookCategory?id=' + bookId
		})
	}
	// 方法
	const toggleControl = () => {
		showControl.value = !showControl.value
	}
	
	function scrollBottom(){
		// for(let i=0;i<novel.value.chapters.length;i++){
		// 	// console.log(novel.value.chapters[i])
		// 	if(chapterId.value==novel.value.chapters[i].id){
		// 		uni.navigateTo({
		// 		  url: `/pages/bookContent/bookContent?bookId=${bookId}&chapterId=${novel.value.chapters[i+1].id}`
		// 		});
		// 		// chapterId.value=novel.value.chapters[i+1].id
		// 		// let progress = {
		// 		// 	chapterId: chapterId.value
		// 		// }
		// 		// localStorage.setItem(`bookProgress_${bookId}`, JSON.stringify(progress) );
		// 		// requestDetail()
		// 		// requestContent()
		// 		// scrollTop.value=0
		// 		// console.log(scrollTop.value)
		// 		// console.log("翻页")
		// 		break
		// 	}
		// }
	}

	const toggleNight = () => {
		isNight.value = !isNight.value
	}

	const changeFontSize = (size) => {
		fontSize.value = Math.max(12, Math.min(24, fontSize.value + size))
	}
	const showCatalog = ref(false);
	const popupRef = ref(null);
	const showChapterList = () => {
		popupRef.value.open()
	}

	const onScroll = (e) => {
		// uni.getSystemInfo({
		//     success: function (res) {
		//         console.log(res.screenHeight );
		//         console.log(res.pixelRatio);
		//         console.log(res.windowWidth);
		//         console.log(res.windowHeight);
		//         console.log(res.language);
		//         console.log(res.version);
		//         console.log(res.platform);
		//     }
		// });
		// console.log(e.detail.scrollTop)
		const scrollTop = e.detail.scrollTop
		const maxScroll = e.detail.scrollHeight -667
		progress.value = Math.round((scrollTop / maxScroll) * 100) || 0
		if(progress.value==100){
			// console.log(novel.value.chapters[0])
			
		}
	}

	function requestContent() {
		uni.request({
			url: baseUrl + '/content/get?chapterId=' + chapterId.value,
			header: {
				'Authorization': authorization
			},
			success: (res) => {
				if (res.data.data.chapterTitle.length > 10) {
					res.data.data.chapterTitle = res.data.data.chapterTitle.substring(0, 12) + '...'
				}
				bookTitle.value = res.data.data.chapterTitle
				currentChapter.value = '第' + res.data.data.chapterIndex + '章'
				content.value= res.data.data.content
				// console.log(novel)
			}
		})
	}

	function requestDetail() {
		uni.request({
			url: baseUrl + '/book/detail?id=' + bookId,
			header: {
				'Authorization': authorization
			},
			success: (res) => {
				novel.value = res.data.data
				// console.log(novel)
			}
		})
	}

	const goToChapter = (chapterId) => {


		uni.navigateTo({
			url: `/pages/bookContent/bookContent?bookId=${bookId}&chapterId=${chapterId}`
		});
	};

	onLoad(option => {
		console.log(option.bookId)
		authorization = localStorage.getItem("Authorization")
		loginBefore()
		if (option.bookId != null) {
			bookId = option.bookId
			chapterId.value = option.chapterId
			let progress = {
				chapterId: chapterId.value
			}
			localStorage.setItem(`bookProgress_${bookId}`, JSON.stringify(progress) );
			requestDetail()
			requestContent()
		}
	})
	
	onReachBottom(()=>{
		// console.log('翻页')
		for(let i=0;i<novel.value.chapters.length;i++){
			// console.log(novel.value.chapters[i])
			if(chapterId.value==novel.value.chapters[i].id){
				setTimeout(()=>{
					uni.navigateTo({
					  url: `/pages/bookContent/bookContent?bookId=${bookId}&chapterId=${novel.value.chapters[i+1].id}`
					});
				},1000)
				// chapterId.value=novel.value.chapters[i+1].id
				// let progress = {
				// 	chapterId: chapterId.value
				// }
				// localStorage.setItem(`bookProgress_${bookId}`, JSON.stringify(progress) );
				// requestDetail()
				// requestContent()
				// scrollTop.value=0
				// console.log(scrollTop.value)
				// console.log("翻页")
				break
			}
		}
	})
</script>

<style lang="scss" scoped>
	body {
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
	}

	.container {
		// height: 100vh;
		background-color: #f5eee5;
		transition: background-color 0.3s;

		&.night {
			background-color: #121212;
			color: #a0a0a0;

			.header,
			.footer {
				background: rgba(0, 0, 0, 0.8) !important;
				color: #a0a0a0;
			}
		}
	}

	.header {
		position: fixed;
		top: 20;
		left: 0;
		right: 0;
		padding: 16px;
		background: rgba(255, 255, 255, 0.9);
		display: flex;
		justify-content: space-between;
		align-items: center;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

		.left {
			display: flex;
			align-items: center;

			.back-icon {
				margin-right: 16px;
				font-weight: bold;
				font-size: 20px;
			}

			.title {
				max-width: 400px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				font-size: 18px;
			}
		}

		.chapter {
			font-size: 16px;
		}
	}

	.content {
		padding-top: 40rpx;
		// height: calc(100vh - 60rpx);
		padding-bottom: 300rpx;
		.text {
			text-indent: 2em;
			letter-spacing: 0.5px;
			line-height: 1.7;
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 16px;
		background: rgba(255, 255, 255, 0.9);
		box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);

		.progress {
			text-align: center;
			margin-bottom: 16px;
			font-size: 14px;
		}

		.controls {
			display: flex;
			justify-content: space-around;

			.btn {
				padding: 12px 24px;
				border-radius: 8px;
				background: #e0e0e0;
				font-size: 14px;
				cursor: pointer;
				transition: background-color 0.3s;

				&:hover {
					background: #d0d0d0;
				}
			}
		}
	}

	.catalog {
		padding: 20px;
		background-color: #fff;
		height: 100vh;
		width: 250px;
	}

	.catalog-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.chapter-list {
		margin-top: 10px;
	}

	.chapter-title {
		font-size: 16px;
		padding: 10px 0;
	}

	.chapter-divider {
		height: 1px;
		background-color: #eee;
	}
</style>